package com.ifcar.app.view;

import com.ifcar.app.util.ThemeSettingsHelper;
import com.ifcar.app.activity.R;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation.AnimationListener;
import android.widget.TabHost;
import android.widget.TabWidget;

/**
 * 可以实现背景动画的TabWidget
 * 
 * @author wjying
 */
public class MyTabWidget extends TabWidget {
	private View mAnimationView;

	private AnimationViewCallback mAnimationViewCallback;

	private int mCurrentIndex = -1;

	private TabHost mTabHost;

	private boolean mAnimationFront;
	
	private boolean mInEditTab;
	
	private boolean mNeedScroll;

	public MyTabWidget(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	public MyTabWidget(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public MyTabWidget(Context context) {
		super(context);
	}

	@Override
	protected void onLayout(boolean changed, int left, int top, int right,
			int bottom) {
		super.onLayout(changed, left, top, right, bottom);
		if (mCurrentIndex != -1 && getChildCount() > 0) {
			View currentTabView = getChildTabViewAt(mCurrentIndex);
			mAnimationView.layout(currentTabView.getLeft(),
					currentTabView.getTop(), currentTabView.getRight(),
					currentTabView.getBottom());
		}

        if (mNeedScroll || mCurrentIndex == getTabCount() - 1 || mCurrentIndex == 0) {
            mNeedScroll = false;
            ViewGroup parent = (ViewGroup) getParent();

            if (parent != null) {
                if (parent instanceof ScrollTabs) {
                    ((ScrollTabs) parent).scrollToPosition(mCurrentIndex);
                } else if (parent instanceof VerticalScrollTabs) {
                    ((VerticalScrollTabs) parent).scrollToPosition(mCurrentIndex);
                }
            }
        }         
	}
	
    public void scrollToCurrent() {
        mNeedScroll = true;
        requestLayout();
    }

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

		if (mCurrentIndex == -1) {
			return;
		}

		View currentTabView = getChildTabViewAt(mCurrentIndex);
		if (mAnimationViewCallback != null) {
			mAnimationViewCallback.onPrepareMeasure(currentTabView,
					mAnimationView);
		}

		if (mAnimationView != null) {
			widthMeasureSpec = MeasureSpec.makeMeasureSpec(
					currentTabView.getMeasuredWidth(), MeasureSpec.EXACTLY);
			heightMeasureSpec = MeasureSpec.makeMeasureSpec(
					currentTabView.getMeasuredHeight(), MeasureSpec.EXACTLY);
			mAnimationView.measure(widthMeasureSpec, heightMeasureSpec);
		}
	}

	@Override
	public void dispatchDraw(Canvas canvas) {
		boolean needInvalidate = false;

		if (!mAnimationFront) {
			needInvalidate = drawAnimationView(canvas);
		}

		super.dispatchDraw(canvas);

		if (mAnimationFront) {
			needInvalidate = drawAnimationView(canvas);
		}

		if (needInvalidate) {
			invalidate();
		}
	}

	private boolean drawAnimationView(Canvas canvas) {
		if (mCurrentIndex != -1 && mAnimationView != null) {
			// 当有开始动画时,在本次invalidate不开始动画,下次invalidate开始
			Animation a = mAnimationView.getAnimation();
			final long startTime = a != null && a.getStartOffset() > 0 ? a
					.getStartTime() : 0;

			drawChild(canvas, mAnimationView, getDrawingTime());

			if (startTime == -1) {
				a.setStartTime(-1);
				a.setStartOffset(0);
			}
			return a != null && !a.hasEnded();
		}
		return false;
	}
	
	public void setEditMode(boolean b) {
		mInEditTab = b;
	}

	@Override
	public void setCurrentTab(int index) {
		super.setCurrentTab(index);
		final int last = mCurrentIndex;
		mCurrentIndex = index;

		if (mInEditTab) {
			return;
		}
		
		Animation a = null;
		if (last != -1 && index != -1 && index != last
				&& mAnimationViewCallback != null && mAnimationView != null) {
			a = mAnimationViewCallback.createAnimation(index, last);
		}

		if (a != null) {
			// 设置动画延时,作用在drawAnimationView
			a.setStartOffset(10000);
			a.setDuration(100);
			View currentTabView = getChildTabViewAt(index);
			mAnimationView.offsetLeftAndRight(currentTabView.getLeft()
					- mAnimationView.getLeft());
			mAnimationView.offsetTopAndBottom(currentTabView.getTop()
					- mAnimationView.getTop());
			mAnimationView.setAnimation(a);
			invalidate();
		}
	}

	@Override
	public void removeAllViews() {
		super.removeAllViews();
		mCurrentIndex = -1;
	}

	public void setAnimaitonViewFront(boolean front) {
		mAnimationFront = true;
		invalidate();
	}

	public void setAnimaitonView(View view) {
		setAnimaitonView(view, getDefaultAnimationViewCallback());
	}

	public void setAnimaitonView(View view, AnimationViewCallback callback) {
		mAnimationView = view;
		mAnimationViewCallback = callback;
	}

	public View getAnimationView() {
		return mAnimationView;
	}

	protected AnimationViewCallback getDefaultAnimationViewCallback() {
		return new AnimationViewCallback() {

			@Override
			public void onPrepareMeasure(View currentTabView, View animationView) {
				// View indicatorView =
				// currentTabView.findViewById(R.id.comment_tab_indicator);
				View indicatorBgView = animationView
						.findViewById(R.id.indicator_bg);
				ViewGroup.LayoutParams lp = indicatorBgView.getLayoutParams();
				lp.width = indicatorBgView.getBackground().getIntrinsicWidth();// indicatorView.getMeasuredWidth();
				lp.height = indicatorBgView.getBackground()
						.getIntrinsicHeight();// indicatorView.getMeasuredHeight();
			}

			@Override
			public Animation createAnimation(int current, int last) {
				TranslateAnimation animation = new TranslateAnimation(
						Animation.RELATIVE_TO_SELF, last - current,
						Animation.RELATIVE_TO_SELF, 0,
						Animation.RELATIVE_TO_SELF, 0,
						Animation.RELATIVE_TO_SELF, 0);
				animation.setDuration(60);
				animation.setInterpolator(getContext(),
						android.R.anim.decelerate_interpolator);
				return animation;
			}

		};
	}

	public void setTabHost(TabHost tabHost) {
		mTabHost = tabHost;
	}

	// 以下方法是tab切换在动画完成之后进行，暂不删除
	// private void callSetCurrentTab(int index) {
	// mTabHost.setCurrentTab(index);
	// mTabHost.getTabContentView().requestFocus(View.FOCUS_FORWARD);
	// }
	//
	// @Override
	// public void addView(View child) {
	// super.addView(child);
	// child.setOnClickListener(new TabClickListener(getTabCount() - 1));
	// }
	//
	// private class TabClickListener implements OnClickListener {
	//
	// private final int mTabIndex;
	//
	// private TabClickListener(int tabIndex) {
	// mTabIndex = tabIndex;
	// }
	//
	// public void onClick(View v) {
	// final int last = mCurrentIndex;
	// final int index = mTabIndex;
	//
	// if (mCurrentIndex == index) {
	// return;
	// }
	//
	// Animation a = null;
	// if (last != -1 && index != -1 && mAnimationViewCallback != null
	// && mAnimationView != null) {
	// a = mAnimationViewCallback.createAnimation(index, last);
	// }
	// if (a == null) {
	// callSetCurrentTab(index);
	// } else {
	// setCurrentTab(index);
	// MyAnimationListener listener = new MyAnimationListener();
	// listener.mTabIndex = index;
	// a.setAnimationListener(listener);
	// View currentTabView = getChildTabViewAt(index);
	// mAnimationView.offsetLeftAndRight(currentTabView.getLeft()
	// - mAnimationView.getLeft());
	// mAnimationView.offsetTopAndBottom(currentTabView.getTop()
	// - mAnimationView.getTop());
	// mAnimationView.startAnimation(a);
	// }
	// }
	// }
	//
	// private class MyAnimationListener implements AnimationListener {
	// private int mTabIndex;
	//
	// private Runnable mSetCurrentTabRunnable = new Runnable() {
	// @Override
	// public void run() {
	// callSetCurrentTab(mTabIndex);
	// }
	// };
	//
	// @Override
	// public void onAnimationStart(Animation animation) {
	// }
	//
	// @Override
	// public void onAnimationRepeat(Animation animation) {
	// }
	//
	// @Override
	// public void onAnimationEnd(Animation animation) {
	// invalidate();
	// post(mSetCurrentTabRunnable);
	// // callSetCurrentTab(mTabIndex);
	// }
	// };

	public interface AnimationViewCallback {
		/**
		 * 调用此方法时,currentTabView已经measure过，即将measure animationView<br/>
		 * animationView的measure长和宽和currentTabView一致<br/>
		 * 可以在此法中设置animationView的子View的LayoutParam
		 * 
		 * @param currentTabView
		 * @param animationView
		 */
		public void onPrepareMeasure(View currentTabView, View animationView);

		public Animation createAnimation(int current, int last);
	}
}
